<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-card shadow="always">
          <el-steps :active="active" finish-status="success">
            <el-step :title="courseName" description="课程名称"></el-step>
            <el-step :title="chapterName" description="章节名称"></el-step>
            <el-step :title="sonChaepterName" description="子章节"></el-step>
          </el-steps>
        </el-card>
        <el-card shadow="hover">
          <el-form
            ref="form"
            :model="courseInfo"
            label-width="80px"
            v-loading="loading"
            :element-loading-text="uploadText"
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.8)"
          >
            <el-form-item label="课程资源">
              <el-upload
                class="upload-demo"
                action="#"
                :on-remove="handleRemove_courseMaterial"
                :before-remove="beforeRemove"
                :auto-upload="false"
                multiple
                :on-change="handleChange_courseMaterial"
                ref="upload"
              >
                <el-button slot="trigger" size="small" type="primary"
                  >选取文件</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="success"
                  @click="submitUploadCourseMaterrial"
                  >上传到服务器</el-button
                >
              </el-upload>
            </el-form-item>
       <el-form-item>
              <router-link
                :to="{
                  name: 'uploadCourse',
                  query: { courseId: courseId },
                }"
              >
                <el-button size="small" type="info">继续添加课程</el-button>
              </router-link>
            </el-form-item>
          </el-form>
          </el-form>
          <el-progress
            :percentage="uploadPercentage"
            v-show="progressSignal"
          ></el-progress>
        </el-card>
      </el-col>
      <el-col :span="12">
        <div v-show="showMaterrial">
          <el-card class="box-card">
            <el-row>
              <span v-for="item in materrialNames" :key="item.courseMaterialId">
                <el-col :span="8">
                  <el-tag
                    closable
                    :disable-transitions="false"
                    @close="handleClose(item)"
                    :type="item.type"
                    :class="item.courseMaterialId"
                    >{{ item.materialName }}</el-tag
                  ></el-col
                >
              </span>
            </el-row>
          </el-card>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import DropdownMenu from "@/components/Share/DropdownMenu";
import {
  getCourseInfo,
  addCourseMaterrial,
  getCourseMaterrial,
  deleteCourseMaterrial,
  submitUploadCourseMaterrial,
} from "../uploadCourseMaterrial_Admin/uploadCourseMaterrial.js";
import $ from "jquery";
import moment from "moment";
import { formatTime } from "@/utils/index.js";
import { AddOrSublineDays } from "@/utils/TimeUitls.js";
import {
  isNull,
  warnInfo,
  successInfo,
  getHost,
  getCookie,
  getTokenSign,
  getToken,
} from "../../utils/commonUtils.js";
export default {
  name: "Documentation",
  components: { DropdownMenu },
  data() {
    return {
      uploadText: "拼命上传中，请耐心等待",
      tokenKey: getTokenSign(), //token标识
      token: getToken(), //token
      progressSignal: false,
      uploadPercentage: 0,
      loading: false,
      active: 3,
      courseId: undefined,
      courseIds: [],
      courseInfo: {},
      courseMaterrialList: [],
      materrialInfo: {
        courseId: undefined,
        fileInfo: [],
      },
      showMaterrial: false,
      materrialNames: [],
      tagType: ["", "success", "info", "warning", "danger"],
      courseName: undefined,
      chapterName: undefined,
      sonChaepterName: undefined,
    };
  },
  watch: {
    materrialNames(val) {
      if (val.length > 0) {
        this.showMaterrial = true;
      } else {
        this.showMaterrial = false;
      }
    },
  },
  created() {
    this.courseId = this.$route.query.courseId;
    this.getCourseInfo();
    this.getCourseMaterrial();
  },
  methods: {
    //继续添加课程
    goOnAddCourse() {
      this.$router.push({
        path: "../uploadCourse_CourseAmin/index",
        query: {
          courseId: this.courseId,
          courseAdmin: true,
          admin_courseId: this.courseId,
        },
      });
    },
    /**
     * 获取已经上传的课程资料
     * **/
    getCourseMaterrial() {
      const _this = this;
      var courseMaterial = {
        courseId: this.courseId,
      };
      getCourseMaterrial(courseMaterial).then((response) => {
        this.materrialNames = response.data;
        var i = 0;
        $(_this.materrialNames).each(function (index, val) {
          var tagTypeLength = _this.tagType.length;
          _this.materrialNames[i++].type = _this.tagType[i % tagTypeLength];
        });
      });
    },
    /**
     * 处理标签的关闭
     * **/
    handleClose(tag) {
      var materrial = {
        courseMaterialId: tag.courseMaterialId,
      };
      deleteCourseMaterrial(materrial).then((response) => {
        this.getCourseMaterrial();
      });
      // this.materrialNames.splice(this.dynamicTags.indexOf(tag), 1);
    },
    /**
     * 创建课程信息
     */
    addCourseMaterrial() {
      const _this = this;
      if (this.courseMaterrialList.length > 0) {
        if (this.materrialInfo.fileInfo.length <= 0) {
          warnInfo(_this, "您还未上传已选择的资料");
          return;
        }
      } else {
        warnInfo(_this, "您未添加任何资料");
        return;
      }

      _this.materrialInfo.courseId = this.courseId;
      addCourseMaterrial(_this.materrialInfo).then((response) => {
        (_this.courseMaterrialList = []), (_this.materrialInfo.fileInfo = []);
        _this.getCourseMaterrial();
      });
    },
    /**
     * 获取课程信息
     */
    getCourseInfo() {
      const _this = this;
      let courseForm = {
        courseId: this.courseId,
      };
      getCourseInfo(courseForm).then((response) => {
        this.courseName = response.data.topCourseName;
        this.chapterName = response.data.parentCourseName;
        this.sonChaepterName = response.data.courseName;
      });
    },
    /**
     * 提交课程资料
     * **/
    submitUploadCourseMaterrial() {
      const _this = this;
      submitUploadCourseMaterrial(_this);
      // if (this.courseMaterrialList.length > 0) {
      //   const formData = new FormData();
      //   $(this.courseMaterrialList).each(function (index, val) {
      //     formData.append("files[" + index + "]", val.raw);
      //     formData.append("fileNames[" + index + "]", _this.token);
      //   });
      //   _this.loading = true;
      //   this.progressSignal = true;
      //   //上传文件
      //   var stopSignal = false;
      //   $.ajax({
      //     url: getHost() + "/fileCenter/file/uploadCourseMaterrials",
      //     data: formData,
      //     dataType: "json",
      //     type: "post",
      //     processData: false, // 告诉jQuery不要去处理发送的数据
      //     contentType: false, // 告诉jQuery不要去设置Content-Type请求头
      //     //加上这句话,允许浏览器向服务器跨域请求时携带cookie
      //     xhrFields: {
      //       withCredentials: true,
      //     },
      //     crossDomain: true,
      //     success: function (data) {
      //       stopSignal = true;
      //       _this.loading = false;
      //       _this.progressSignal = false;
      //       _this.materrialInfo.fileInfo = data.data;
      //       _this.addCourseMaterrial();
      //     },
      //     error: function (data) {},
      //   });

      //   //开始执行定时器获取上传进度
      //   var timer = window.setInterval(() => {
      //     setTimeout(() => {
      //       $.ajax({
      //         url: getHost() + "/fileCenter/file/getUploadProgress",
      //         data: {
      //           sign: "uploadCourseMaterrials",
      //         },
      //         dataType: "json",
      //         type: "post",
      //         //加上这句话,允许浏览器向服务器跨域请求时携带cookie
      //         xhrFields: {
      //           withCredentials: true,
      //         },
      //         crossDomain: true,
      //         beforeSend: function (request) {
      //           request.setRequestHeader(_this.tokenKey, _this.token);
      //         },
      //         success: function (data) {
      //           var progress = parseInt(data.data);
      //           _this.uploadPercentage = progress;
      //           if (progress >= 100 || stopSignal) {
      //             _this.uploadPercentage = 100;
      //             _this.progressSignal = false;
      //             _this.uploadPercentage = 0;
      //             //停止进行
      //             clearInterval(timer);
      //           }
      //         },
      //         error: function (data) {
      //           clearInterval(timer); //停止进行
      //         },
      //       });
      //     }, 0);
      //   }, 300);
      // } else {
      //   warnInfo(_this, "您未选择任何文件");
      // }
    },
    handleRemove_courseMaterial(file, fileList) {},
    handleChange_courseMaterial(file, fileList) {
      this.courseMaterrialList = fileList;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../styles/common.css";
</style>
